from rest_framework.generics import CreateAPIView
from rest_framework.views import APIView
from carts.serializers import CartSkuSerializer
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection
from goods.models import SKU
from rest_framework.response import Response
from .serializers import SaveOrderSerializer


# 订单结算
class OrderSettlementView(APIView):
    # 登录验证
    permission_classes = [IsAuthenticated]

    def get(self, request):
        redis_cli = get_redis_connection("cart")
        user = request.user
        # 获取商品编号和数量
        cart_dict = redis_cli.hgetall("cart%d" % user.id)
        # 获取被选中的商品编号
        cart_selected = redis_cli.smembers("cart_selected%d" % user.id)
        # bytes -->  int
        cart_dict = {int(sku_id): int(count) for sku_id, count in cart_dict.items()}
        # 查询选中的商品对象列表
        skus = SKU.objects.filter(pk__in=cart_selected)
        # 添加需要序列化返回的属性
        for sku in skus:
            print(sku.id)
            sku.count = cart_dict[sku.id]
            sku.selected = True
        # 序列化
        serializer = CartSkuSerializer(skus, many=True)
        # 构造返回对象
        result = {
            "freight": 10,
            "skus": serializer.data
        }
        return Response(result)


class SaveOrderView(CreateAPIView):
    """ 接收参数:收货地址 支付方式
        返回参数:订单编号 """
    permission_classes = [IsAuthenticated]
    serializer_class = SaveOrderSerializer
